package RabbitMq.Component;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Map;

/**
 * @ClassName RabbitConsumerChannelAwareMessage
 * @Description TDD
 * @Author 混沌酱
 * @Date 2023-10-13 16:45
 * @Version 1.0
 **/
@Component
public class RabbitConsumerChannelAwareMessage implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        // 消息投递序号，消息每次投递该值都会+1
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            byte[] body = message.getBody();
            ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(body));
            Map<String,String> msgMap = (Map<String,String>) objectInputStream.readObject();
            String messageId = msgMap.get("messageId");
            String messageData = msgMap.get("messageContent");
            String createTime = msgMap.get("sendTime");
            objectInputStream.close();
            System.out.println("rabbitConsumer:  messageId:"+messageId+"  messageData:"+messageData+"  createTime:"+createTime);
            System.out.println("消费的队列名："+message.getMessageProperties().getConsumerQueue());
            /**
             * 签收消息
             * 参数1：消息投递序号
             * 参数2：是否一次可以签收多条消息，true:是；false:否
             */
            channel.basicAck(deliveryTag, true);
        }catch (Exception e){
            /**
             * 拒签消息
             * 参数1：消息投递序号
             * 参数2：是否一次可以拒签多条消息，true:是；false:否
             * 参数3：拒签后消息是否重回队列，true:重回队列；false:不重回队列
             */
            System.out.println("消息消费失败！");
            channel.basicNack(deliveryTag, true, true);
            e.printStackTrace();
        }
    }
}
